/**
 * 格式转换工具
 * 提供Markdown到不同格式的转换功能
 */

/**
 * 将Markdown转换为HTML格式
 * @param markdown Markdown内容
 * @param title 文章标题
 * @param includeTitle 是否包含标题
 * @returns HTML格式的内容
 */
export const convertMarkdownToHtml = (markdown: string, title: string = '', includeTitle: boolean = true): string => {
  let htmlContent = markdown
    // 转换标题
    .replace(/^# (.*$)/gm, '<h1>$1</h1>')
    .replace(/^## (.*$)/gm, '<h2>$1</h2>')
    .replace(/^### (.*$)/gm, '<h3>$1</h3>')
    // 转换强调
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    // 转换列表
    .replace(/^\- (.*$)/gm, '<li>$1</li>')
    .replace(/^(\d+)\. (.*$)/gm, '<li>$2</li>')
    // 转换段落
    .replace(/\n\n/g, '</p><p>')
    .replace(/^(?!<[h|li])(.+)(?![>])$/gm, '<p>$1</p>')
    // 转换分割线
    .replace(/---/g, '<hr>');

  // 添加标题
  if (includeTitle && title) {
    htmlContent = `<h1>${title}</h1>\n${htmlContent}`;
  }

  // 添加HTML文档结构
  const fullHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title || '导出文档'}</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            font-size: 28px;
            margin: 20px 0;
            color: #2c3e50;
        }
        h2 {
            font-size: 24px;
            margin: 16px 0;
            color: #2c3e50;
        }
        h3 {
            font-size: 20px;
            margin: 12px 0;
            color: #2c3e50;
        }
        p {
            margin: 12px 0;
        }
        ul, ol {
            margin: 12px 0;
            padding-left: 24px;
        }
        li {
            margin: 4px 0;
        }
        strong {
            font-weight: 600;
        }
        em {
            font-style: italic;
        }
        hr {
            border: none;
            border-top: 1px solid #e1e5e9;
            margin: 20px 0;
        }
    </style>
</head>
<body>
${htmlContent}
</body>
</html>`;

  return fullHtml;
};

/**
 * 将Markdown转换为微信公众号格式的HTML
 * @param markdown Markdown内容
 * @param title 文章标题
 * @param includeTitle 是否包含标题
 * @returns 微信公众号格式的HTML内容
 */
export const convertMarkdownToWechatFormat = (markdown: string, title: string = '', includeTitle: boolean = true): string => {
  let htmlContent = markdown
    // 转换标题（微信风格）
    .replace(/^# (.*$)/gm, '<h1 style="font-size: 24px; font-weight: bold; margin: 20px 0;">$1</h1>')
    .replace(/^## (.*$)/gm, '<h2 style="font-size: 20px; font-weight: bold; margin: 16px 0;">$1</h2>')
    .replace(/^### (.*$)/gm, '<h3 style="font-size: 16px; font-weight: bold; margin: 12px 0;">$1</h3>')
    // 转换强调
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    // 转换列表（微信风格）
    .replace(/^\- (.*$)/gm, '• $1')
    .replace(/^(\d+)\. (.*$)/gm, '$&')
    // 转换段落
    .replace(/\n\n/g, '</p><p>')
    .replace(/^(?!<[h])(.+)(?![>])$/gm, '<p>$1</p>')
    // 转换分割线
    .replace(/---/g, '<hr style="margin: 20px 0; border: none; border-top: 1px solid #e1e5e9;">');

  // 添加标题
  if (includeTitle && title) {
    htmlContent = `<h1 style="font-size: 24px; font-weight: bold; margin: 20px 0;">${title}</h1>\n${htmlContent}`;
  }

  // 添加微信公众号特定的样式
  const fullHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title || '微信公众号文章'}</title>
    <style>
        body {
            font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.8;
            color: #333;
            padding: 16px;
            background-color: #f8f8f8;
        }
        .rich_media_content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        p {
            margin: 16px 0 !important;
            line-height: 1.8 !important;
        }
        strong {
            font-weight: 600 !important;
        }
        em {
            font-style: italic !important;
        }
    </style>
</head>
<body>
<div class="rich_media_content">
${htmlContent}
</div>
</body>
</html>`;

  return fullHtml;
};

/**
 * 将Markdown转换为纯文本格式
 * @param markdown Markdown内容
 * @param title 文章标题
 * @param includeTitle 是否包含标题
 * @returns 纯文本格式的内容
 */
export const convertMarkdownToPlainText = (markdown: string, title: string = '', includeTitle: boolean = true): string => {
  // 移除Markdown标记
  let plainText = markdown
    // 移除标题标记
    .replace(/^#\s+/gm, '')
    .replace(/^##\s+/gm, '')
    .replace(/^###\s+/gm, '')
    // 移除强调标记
    .replace(/\*\*(.*?)\*\*/g, '$1')
    .replace(/\*(.*?)\*/g, '$1')
    // 移除列表标记
    .replace(/^\-\s+/gm, '• ')
    // 移除分割线
    .replace(/---/g, '');

  // 添加标题
  if (includeTitle && title) {
    plainText = `${title}\n\n${plainText}`;
  }

  return plainText;
};

/**
 * 根据目标格式转换Markdown内容
 * @param markdown Markdown内容
 * @param format 目标格式
 * @param title 文章标题
 * @param options 转换选项
 * @returns 转换后的内容
 */
export const convertMarkdown = (
  markdown: string,
  format: string,
  title: string = '',
  options: { includeTitle?: boolean } = {}
): string => {
  const includeTitle = options.includeTitle ?? true;
  
  switch (format.toLowerCase()) {
    case 'html':
      return convertMarkdownToHtml(markdown, title, includeTitle);
    case 'wechat':
      return convertMarkdownToWechatFormat(markdown, title, includeTitle);
    case 'txt':
      return convertMarkdownToPlainText(markdown, title, includeTitle);
    case 'markdown':
    case 'md':
    default:
      // 对于Markdown格式，如果需要包含标题，则在内容前添加标题
      if (includeTitle && title && !markdown.startsWith(`# ${title}`)) {
        return `# ${title}\n\n${markdown}`;
      }
      return markdown;
  }
};

/**
 * 获取文件扩展名
 * @param format 文件格式
 * @returns 文件扩展名
 */
export const getFileExtension = (format: string): string => {
  switch (format.toLowerCase()) {
    case 'html':
    case 'wechat':
      return 'html';
    case 'markdown':
    case 'md':
      return 'md';
    case 'txt':
      return 'txt';
    case 'pdf':
      return 'pdf';
    case 'docx':
      return 'docx';
    default:
      return 'txt';
  }
};

/**
 * 获取MIME类型
 * @param format 文件格式
 * @returns MIME类型
 */
export const getMimeType = (format: string): string => {
  switch (format.toLowerCase()) {
    case 'html':
    case 'wechat':
      return 'text/html';
    case 'markdown':
    case 'md':
      return 'text/markdown';
    case 'txt':
      return 'text/plain';
    case 'pdf':
      return 'application/pdf';
    case 'docx':
      return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    default:
      return 'application/octet-stream';
  }
};